import { Main } from '@/service/types';
import { useCommonStore } from '../store/common';
import { deepClone } from 'wot-design-uni/components/common/util';
export type CascaderOption = {
  text: string
  value: string
  children?: CascaderOption[]
}

/**
 * 省市区数据
 * @returns
 */
export function useColPickerData(isAll = true, cityName = '全国') {
  const useCommon = useCommonStore();
  // 数据源
  const colPickerData: Main.RegionInfo[] = deepClone(useCommon.commonState.regionInfo);

  // 根据code查找子节点，不传code则返回所有节点
  function findChildrenByCode(data: Main.RegionInfo[], code?: string): Main.RegionInfo[] | null {
    if (!code) {
      return data
    }
    for (const item of data) {
      if (item.id === code) {
        return item.children || null
      }
      if (item.children) {
        const childrenResult = findChildrenByCode(item.children, code)
        if (childrenResult) {
          return childrenResult
        }
      }
    }
    return null
  }

  colPickerData.map((item) => {
    const child = item.children || [];
    child.forEach((childItem) => {
      if (item.name === childItem.name) {
        childItem.name = '所有'
      }
    })
    if (child[0].name !== '所有') {
      child.unshift({
        name: '所有',
        id: ''
      } as Main.RegionInfo)
    }
  })

  if (isAll) {
    colPickerData.unshift({
      name: cityName,
      id: '',
      children: []
    } as Main.RegionInfo)
  }

  return { colPickerData, findChildrenByCode }
}